import axios from 'axios'
import {useUserStore} from '@/stores'
import {ElMessage} from 'element-plus'
import router from "@/router";

const baseURL = 'http://localhost:8080'

const instance = axios.create({
	// 1. 基础地址，超时时间
	baseURL,
	timeout: 10000
})

// 请求拦截器
instance.interceptors.request.use(
	(config) => {
		// 2. 携带token
		const userStore = useUserStore()
		if (userStore.token) {
			config.headers.Authorization = userStore.token
		}
		return config
	},
	(err) => Promise.reject(err)
)

// 响应拦截器
instance.interceptors.response.use(
	(res) => {
		// 1. 统一处理错误
		if (res.status === 200) {
			const headers = res.headers;
			// 设置或者更新token
			if (headers['authorization']) {
				const userStore = useUserStore()
				userStore.token = headers['authorization']
				useUserStore().save()
				console.log("token:" + userStore.token)
			}
			return res.data
		}
		// 3. 处理业务失败
		ElMessage.error(res.data.msg || '服务异常')
		// 4. 摘取核心响应数据
		return Promise.reject(res.data)
	},
	(err) => {
		// 5. 处理 401 错误
		if (err.status === 401) {
			router.push('/login').then(r => {})
		}
		ElMessage.error(err.response.data.msg || '服务异常')
		return Promise.reject(err)
	}
)

export default instance
export {baseURL}